﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;

using NuMetaheuristics;

namespace NuMetaheuristics.Utility
{
    public class ContractSerializer<T>
    {
        public void Serialize(T item, string xmlPath)
        {
            Serialize(item, xmlPath, Enumerable.Empty<Type>());
        }

        public void Serialize(T item, string xmlPath, IEnumerable<Type> knownTypes)
        {
            var serializer = new DataContractSerializer(item.GetType(), knownTypes);
            var writer = new FileStream(xmlPath, FileMode.Create);

            using (writer)
            {
                serializer.WriteObject(writer, item);
                //try
                //{
                    
                //}
                //catch (Exception e)
                //{
                //    System.Console.WriteLine("Exception caught: " + e);
                //}
                writer.Close();
            }
        }

        public T Deserialize(string xmlPath)
        {
            return Deserialize(xmlPath, Enumerable.Empty<Type>());
        }
        
        public T Deserialize(string xmlPath, IEnumerable<Type> knownTypes)
        {
            var serializer = new DataContractSerializer(typeof(T), knownTypes);
            var reader = new FileStream(xmlPath, FileMode.Open);

            T item = default(T);

            using (reader)
            {
                try
                {
                    item = (T)serializer.ReadObject(reader);
                }
                catch (Exception e)
                {
                    System.Console.WriteLine("Exception caught: " + e);
                }
                reader.Close();
            }

            return item;
        }
    }
}
